package com.example.dingtalklogin.service.executor;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.dingtalklogin.dao.User;
import com.example.dingtalklogin.dao.UserRepository;
import com.example.dingtalklogin.service.dto.DingtalkUnBindingCmd;
import freemarker.template.utility.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
public class DingtalkUnBindingCmdExe {

    private UserRepository userRepository;

    @Autowired
    public DingtalkUnBindingCmdExe(UserRepository userRepository){
        this.userRepository = userRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public void execute(DingtalkUnBindingCmd cmd){
        cmd.validate();
        User user = userRepository.getById(cmd.getUserId());
        if(user != null && StringUtils.hasLength(user.getDingtalkUnionId())){
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(User::getDingtalkUnionId, null);
            updateWrapper.set(User::getLastModifiedDate, LocalDateTime.now());
            updateWrapper.set(User::getLastModifiedBy, cmd.getOpUserId());
            updateWrapper.eq(User::getId, user.getId());
            userRepository.update(updateWrapper);
        }
    }
}
